package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BaseBusinessException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  ciggar
 * create-date: 2019/8/1-下午4:47
 * 参数校验
 */
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Reference(check = false)
    private IMemberService memberService;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockMapper stockMapper;

    /**
     * 验证用户合法性
     * @return
     */

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 验证用户信息，是否登陆状态
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        QueryMemberRequest request = new QueryMemberRequest(createOrderContext.getUserId());
        request.requestCheck();

        // 验证商品购买信息：库存是否足够，是否超出限购量
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            // 根据商品id查出商品的库存以及限购数量
            Stock sto = new Stock();
            sto.setItemId(cartProductDto.getProductId());
            Stock stock = stockMapper.selectOne(sto);
            if (cartProductDto.getProductNum() > stock.getStockCount()){
                throw new BaseBusinessException(SysRetCodeConstants.UNDER_STOCK.getCode(),
                        SysRetCodeConstants.UNDER_STOCK.getMessage());
            }

            if (cartProductDto.getProductNum() > stock.getRestrictCount()){
                throw new BaseBusinessException(SysRetCodeConstants.OUT_OF_RANGE.getCode(),
                        SysRetCodeConstants.OUT_OF_RANGE.getMessage());
            }
        }
        log.info("用户校验完成");
        return true;
    }
}
